package cn.kwq.pcsystem.utils;

import cn.hutool.core.lang.Validator;
import cn.kwq.pcsystem.entity.User;
import cn.kwq.pcsystem.exception.UserExistException;
import cn.kwq.pcsystem.exception.UserFormatException;
import cn.kwq.pcsystem.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created with IntelliJ IDEA.
 * 业务工具类
 * @Author: kwq
 * @Date: 2023/02/28/15:40
 * @Description:
 */
@Slf4j
public class CheckUtils {

    @Autowired
    UserMapper userMapper;

    public static CheckUtils doCheck(){
        return new CheckUtils();
    }

    /**
     * 检查用户邮箱和手机格式是否正确
     * @param phone
     * @param email
     */
    public CheckUtils checkFormat(String phone, String email) throws UserFormatException {
        if (!Validator.isEmail(email)){
            if (!Validator.isMobile(phone)) {
                log.error(phone+"手机号格式错误");
                throw new UserFormatException("手机号格式错误");
            }
            log.error(email+"邮箱格式错误");
            throw new UserFormatException("邮箱格式错误");
        }
        return this;
    }
    /**
     * 检查该用户的手机号 邮箱 名字是否已注册
     *
     * @param userName
     * @param phone
     * @param email
     */
    public CheckUtils checkExist(String userName, String phone, String email) throws UserExistException {
        StringBuilder str=new StringBuilder();

        QueryWrapper<User> w1=new QueryWrapper<>();
        w1.eq("phone",phone);
        User u1 = userMapper.selectOne(w1);
        if (u1!=null){
            str.insert(0,"手机号已被注册");
            log.error(phone+str);
            throw new UserExistException(str.toString());
        }

        QueryWrapper<User> w2=new QueryWrapper<>();
        w2.eq("user_name",userName);
        User u2 = userMapper.selectOne(w2);
        if (u2!=null){
            str.insert(0,"用户名已存在");
            log.error(userName+str);
            throw new UserExistException(str.toString());

        }

        QueryWrapper<User> w3=new QueryWrapper<>();
        w3.eq("email",email);
        User u3 = userMapper.selectOne(w3);
        if (u3!=null){
            str.insert(0,"邮箱已被注册");
            log.error(email+str);
            throw new UserExistException(str.toString());
        }
        return this;
    }
}
